Page({
  data: {
    isLoggedIn: false,
    userInfo: {},
    tempUserInfo: {}, // 临时存储用户信息
    points: 0,
    hasCheckedIn: false,
    checkTimer: null,
    // 随机头像列表
    avatarList: [
      'https://tryokey.oss-cn-beijing.aliyuncs.com/avatar/37f82d5a37d07f1abb4f31f2daeacb9f.jpg',
      'https://tryokey.oss-cn-beijing.aliyuncs.com/avatar/6-22061Z91910.jpg',
      'https://tryokey.oss-cn-beijing.aliyuncs.com/avatar/72cdb417c865.jpg',
      'https://tryokey.oss-cn-beijing.aliyuncs.com/avatar/8fc0b351605b4db2af7d72bb85eed293.jpeg',
      'https://tryokey.oss-cn-beijing.aliyuncs.com/avatar/images%20%281%29.jpg',
      'https://tryokey.oss-cn-beijing.aliyuncs.com/avatar/images%20%282%29.jpg',
      'https://tryokey.oss-cn-beijing.aliyuncs.com/avatar/images%20%283%29.jpg'
    ],
    // 随机昵称列表
    nicknames: [
      '星河浪子', '快乐的风', '紫色的梦', '落叶无声', '夜空中的星',
      '随风而去', '小小蓝天', '梦回故里', '清晨的露珠', '冰雪之恋',
      '红尘客栈', '幸福的海', '柠檬小子', '夏日的阳光', '梦中的花',
      '苍茫大地', '温柔如水', '天使微笑', '烟雨江南', '暖阳之下',
      '薄荷味道', '狐狸的尾巴', '白雪公主', '漠然心动', '蓝色的梦',
      '独行侠', '萤火虫的夜', '傻傻的笑', '纸飞机', '天际远方',
      '暖风习习', '一颗星星', '紫藤花开', '暖心阳光', '梦想的翅膀',
      '青云志', '小小松鼠', '无畏前行', '微笑的眼睛', '黎明的曙光',
      '月光森林', '心跳瞬间', '飘逸的风', '海的深蓝', '一缕清风',
      '迷失的旅人', '诗和远方', '风中的羽毛', '蓝色的海', '独自飞翔',
      '神秘的面纱', '心中的火焰', '一笑倾城', '秋水共长天', '坚强的心',
      '荷叶飘香', '星辰大海', '画中的女孩', '狂风中的微笑', '暗夜精灵',
      '星空之上', '寂静的夜', '微风吹拂', '暖心独行', '远方的歌声',
      '梦里花落知多少', '随风漂泊', '潮汐的微笑', '晴天娃娃', '沉默的羔羊',
      '时光之海', '落英缤纷', '无声的舞者', '青涩年华', '追风少年',
      '清风拂面', '漫步云端', '荒野游侠', '橙色的天空', '旋转的木马',
      '星星之火', '冷月孤星', '暖风拂柳', '流光溢彩', '落日余晖',
      '迷失的心', '清澈如水', '微笑的阳光', '无畏风雨', '逐梦之旅',
      '紫陌红尘', '飞翔的鸽子', '苍狼野犬', '绽放的花朵', '温柔岁月',
      '海的风', '望月听风', '心灵的栖息地', '飞舞的彩蝶', '隐秘的角落'
    ],
    hasSignedIn: false, // 今日是否已签到
    readCount: 0,
    shareCount: 0,
    buttonTop: 0,
    buttonLeft: 0,
    windowHeight: 0,
    windowWidth: 0,
    isDragging: false,
    showFullGif: false,  // 新增：控制全屏GIF显示
  },

  onLoad() {
    // 检查是否已经登录
    this.checkLoginStatus();
    // 检查今日是否已签到
    this.checkDailyCheckIn();
    // 启动定时器检查日期变更
    this.startDateCheck();
    // 生成随机头像和昵称
    this.generateRandomUserInfo();
    // 如果已登录，获取积分
    if (this.data.isLoggedIn) {
      this.fetchUserPoints();
    }
    // 获取窗口信息
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      buttonTop: systemInfo.windowHeight - 180,
      buttonLeft: systemInfo.windowWidth - 160,
      windowHeight: systemInfo.windowHeight,
      windowWidth: systemInfo.windowWidth
    });
  },
  gotoindex() {
    const readRecord = wx.getStorageSync('readRecord') || {};
    if (readRecord.count >= 3) {
      wx.showToast({
        title: '今日已达上限',
        icon: "none"
      })
    } else {
      wx.switchTab({
        url: '/pages/index/index',
      })
    }
  },
  gotowe() {
    wx.navigateTo({
      url: '/pages/follow/follow',
    })
  },
  onShow() {
    // 每次页面显示时检查登录状态和签到状态
    this.checkLoginStatus();
    this.checkDailyCheckIn();
    if (this.data.isLoggedIn) {
      // 获取最新积分
      this.fetchUserPoints();
    }
    // 获取今日阅读次数
    const today = new Date().toDateString();
    const readRecord = wx.getStorageSync('readRecord') || {};
    if (readRecord.date === today) {
      this.setData({
        readCount: readRecord.count || 0
      });
    } else {
      this.setData({
        readCount: 0
      });
    }
    // 获取今日分享次数
    const shareCount = this.checkShareCount();
    this.setData({
      shareCount
    });
  },

  onHide() {
    // 页面隐藏时清除定时器
    if (this.data.checkTimer) {
      clearInterval(this.data.checkTimer);
    }
  },

  onUnload() {
    // 页面卸载时清除定时器
    if (this.data.checkTimer) {
      clearInterval(this.data.checkTimer);
    }
  },

  startDateCheck() {
    // 每分钟检查一次是否过了凌晨
    const timer = setInterval(() => {
      this.checkDailyCheckIn();
    }, 60000); // 每分钟检查一次

    this.setData({
      checkTimer: timer
    });
  },

  checkLoginStatus() {
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');

    console.log('检查登录状态:', { token, userInfo });

    if (token && userInfo && userInfo.nickname) {  // 确保userInfo中有nickName
      this.setData({
        isLoggedIn: true,
        userInfo: userInfo
      }, () => {
        console.log('登录状态更新后：', this.data);
      });
    } else {
      console.log('登录验证失败:', {
        hasToken: !!token,
        hasUserInfo: !!userInfo,
        hasNickName: userInfo?.nickName
      });
      this.setData({
        isLoggedIn: false,
        userInfo: {}
      }, () => {
        console.log('未登录状态更新后：', this.data);
      });
    }
  },

  checkDailyCheckIn() {
    const lastCheckIn = wx.getStorageSync('lastCheckIn');
    if (!lastCheckIn) {
      this.setData({ hasCheckedIn: false });
      return;
    }

    const lastCheckInDate = new Date(lastCheckIn);
    const now = new Date();

    // 检查是否是同一天
    const isSameDay =
      lastCheckInDate.getFullYear() === now.getFullYear() &&
      lastCheckInDate.getMonth() === now.getMonth() &&
      lastCheckInDate.getDate() === now.getDate();

    this.setData({
      hasCheckedIn: isSameDay
    });
  },

  handleDailyCheckIn() {
    if (!this.data.isLoggedIn) {
      wx.showToast({
        title: '请先登录后签到',
        icon: 'none'
      });
      return;
    }

    if (this.data.hasCheckedIn) {
      wx.showToast({
        title: '今日已签到 (｡•́︿•̀｡)',
        icon: 'none'
      });
      return;
    }

    // 增加积分
    const newPoints = this.data.points + 2;
    const today = new Date().toISOString(); // 存储完整的时间戳

    this.setData({
      points: newPoints,
      hasCheckedIn: true
    });

    wx.setStorageSync('points', newPoints);
    wx.setStorageSync('lastCheckIn', today);

    // 使用自定义toast
    this.selectComponent('#customToast').showToast('签到成功 (◕‿◕✿)');
  },

  onShareAppMessage() {
    if (!this.data.isLoggedIn) {
      return {
        title: '邀请好友使用小程序',
        path: '/pages/index/index'
      };
    }

    return {
      title: '邀请好友使用小程序，得10积分！',
      path: '/pages/index/index?inviter=' + this.data.userInfo.nickName,
      success: () => {
        // 分享成功后的回调，可以在这里增加积分
        const newPoints = this.data.points + 10;
        this.setData({
          points: newPoints
        });
        wx.setStorageSync('points', newPoints);
        wx.showToast({
          title: '分享成功，获得10积分！',
          icon: 'success'
        });
      }
    };
  },

  // 选择头像事件
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail;
    console.log('选择头像:', avatarUrl);

    this.setData({
      'tempUserInfo.avatarUrl': avatarUrl
    });
  },

  // 输入昵称事件
  onInputNickName(e) {
    const nickName = e.detail.value;
    console.log('输入昵称:', nickName);

    this.setData({
      'tempUserInfo.nickName': nickName
    });
  },

  // 生成随机用户信息
  generateRandomUserInfo() {
    const randomAvatar = this.data.avatarList[Math.floor(Math.random() * this.data.avatarList.length)];
    const randomNickName = this.data.nicknames[Math.floor(Math.random() * this.data.nicknames.length)];

    const randomUserInfo = {
      nickName: randomNickName,
      avatarUrl: randomAvatar,
      gender: 2
    };

    this.setData({
      tempUserInfo: randomUserInfo
    }, () => {
      console.log('随机用户信息已生成：', randomUserInfo);
    });

    return randomUserInfo;
  },

  // 确认登录
  confirmLogin() {
    if (!this.data.tempUserInfo.nickName || !this.data.tempUserInfo.avatarUrl) {
      // 如果没有头像或昵称，重新生成
      this.generateRandomUserInfo();
    }

    wx.showLoading({
      title: '登录中...'
    });

    // 获取登录code
    wx.login({
      success: (res) => {
        if (res.code) {
          console.log('获取code成功：', res.code);
          this.loginWithServer(res.code, this.data.tempUserInfo);
        } else {
          wx.hideLoading();
          wx.showToast({
            title: '登录失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('wx.login 调用失败', err);
        wx.showToast({
          title: '登录失败',
          icon: 'none'
        });
      }
    });
  },

  // 处理登录
  handleLogin() {
    if (this.data.isLoggedIn) {
      return;
    }

    wx.login({
      success: (res) => {
        if (res.code) {
          // 使用临时用户信息或生成新的随机用户信息
          const userInfo = this.data.tempUserInfo.nickName ?
            this.data.tempUserInfo :
            this.generateRandomUserInfo();

          this.loginWithServer(res.code, userInfo);
        } else {
          wx.showToast({
            title: '登录失败',
            icon: 'none'
          });
        }
      }
    });
  },

  // 与服务器通信进行登录
  loginWithServer(code, userInfo) {
    wx.request({
      url: 'https://www.haoyuming.online/api/user/wx/login',
      method: 'POST',
      data: {
        code: code,
        userInfo: userInfo
      },
      success: (res) => {
        if (res.data.code === 200) {
          const { token, userInfo } = res.data.data;

          // 存储用户信息和token
          wx.setStorageSync('token', token);
          wx.setStorageSync('userInfo', userInfo);

          this.setData({
            isLoggedIn: true,
            userInfo: userInfo
          });

          wx.hideLoading();
          wx.showToast({
            title: '登录成功',
            icon: 'success'
          });
        } else if (res.statusCode === 401) {
          // 清除登录信息
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          this.setData({
            isLoggedIn: false,
            userInfo: {}
          });
          wx.showToast({
            title: '登录已过期，请重新登录',
            icon: 'none'
          });
          wx.navigateTo({
            url: '/pages/login/login'
          });
        } else {
          wx.hideLoading();
          wx.showToast({
            title: '登录失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('登录失败:', err);
        wx.hideLoading();
        wx.showToast({
          title: '登录失败',
          icon: 'none'
        });
      }
    });
  },

  // 签到增加积分
  handleSignIn() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 检查今日是否已签到
    const lastCheckIn = wx.getStorageSync('lastCheckIn');
    if (lastCheckIn) {
      const lastDate = new Date(lastCheckIn);
      const today = new Date();

      if (lastDate.getFullYear() === today.getFullYear() &&
        lastDate.getMonth() === today.getMonth() &&
        lastDate.getDate() === today.getDate()) {
        this.setData({
          hasSignedIn: true
        })
        wx.showToast({
          title: '今日已签到，明天再来吧',
          icon: 'none'
        });
        return;
      }
    }
    wx.request({
      url: 'https://www.haoyuming.online/api/user/points/add',
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      data: {
        points: 2,
        source: '每日签到'
      },
      success: (res) => {
        if (res.statusCode === 401) {
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          this.setData({
            isLoggedIn: false,
            userInfo: {}
          });
          wx.showToast({
            title: '登录已过期，请重新登录',
            icon: 'none'
          });
          wx.navigateTo({
            url: '/pages/login/login'
          });
          return;
        }
        console.log('签到响应：', res.data);
        if (res.data.code === 200) {
          // 保存签到时间
          wx.setStorageSync('lastCheckIn', new Date().toISOString());

          wx.showToast({
            title: '签到成功 +2积分',
            icon: 'success'
          });
          // 更新积分显示
          this.setData({
            'userInfo.point': (this.data.userInfo.point || 0) + 2,
            hasSignedIn: true
          });
        } else {
          wx.showToast({
            title: res.data.message || '签到失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('签到失败：', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },

  // 检查签到状态
  checkSignInStatus() {
    const token = wx.getStorageSync('token');
    wx.request({
      url: 'https://www.haoyuming.online/api/user/sign/today',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.statusCode === 401) {
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          this.setData({
            isLoggedIn: false,
            userInfo: {}
          });
          wx.showToast({
            title: '登录已过期，请重新登录',
            icon: 'none'
          });
          wx.navigateTo({
            url: '/pages/login/login'
          });
          return;
        }
        if (res.data.code === 200) {
          this.setData({
            hasSignedIn: res.data.data // true表示今日已签到
          });
        }
      }
    });
  },

  // 签到
  onSignInTap() {
    if (!this.data.isLoggedIn) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    if (this.data.hasSignedIn) {
      wx.showToast({
        title: '今日已签到，明天再来吧',
        icon: 'none'
      });
      return;
    }

    const token = wx.getStorageSync('token');
    wx.request({
      url: 'https://www.haoyuming.online/api/user/sign',
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.code === 200) {
          this.setData({
            hasSignedIn: true
          });
          // 签到成功后重新获取积分
          this.fetchUserPoints();
          wx.showToast({
            title: `签到成功 +${res.data.data}积分`,
            icon: 'none',
            duration: 2000
          });
        } else if (res.data.code === 400 && res.data.msg.includes('已签到')) {
          this.setData({
            hasSignedIn: true
          });
          wx.showToast({
            title: '今日已签到，明天再来吧',
            icon: 'none'
          });
        } else {
          wx.showToast({
            title: res.data.msg || '签到失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },

  // 获取用户积分
  fetchUserPoints() {
    const token = wx.getStorageSync('token');
    if (!token) {
      return;
    }

    wx.request({
      url: 'https://www.haoyuming.online/api/user/point',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.statusCode === 401) {
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          this.setData({
            isLoggedIn: false,
            userInfo: {}
          });
          wx.showToast({
            title: '登录已过期，请重新登录',
            icon: 'none'
          });
          wx.navigateTo({
            url: '/pages/login/login'
          });
          return;
        }
        console.log('获取积分响应：', res.data);
        if (res.data.code === 200) {
          const userInfo = this.data.userInfo;
          userInfo.point = res.data.data.points;
          this.setData({
            userInfo: userInfo,
            points: res.data.data.points
          });
        }
      },
      fail: (err) => {
        console.error('获取积分失败：', err);
      }
    });
  },

  // 跳转到抽奖页面
  goToLottery() {
    if (!this.data.isLoggedIn) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    wx.navigateTo({
      url: '/pages/lottery/lottery'
    });
  },

  // 显示作者二维码
  showAuthorQRCode() {
    wx.navigateTo({
      url: '/pages/qrcode/qrcode'
    });
  },
  goToQRCode() {
    wx.navigateTo({
      url: '/pages/qrcode/qrcode',
    })
  },
  // 跳转到积分记录页面
  goToPointsHistory() {
    if (!this.data.isLoggedIn) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    wx.navigateTo({
      url: '/pages/points-history/points-history'
    });
  },

  // 跳转到奖品兑换页面
  goToRewards() {
    if (!this.data.isLoggedIn) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    wx.navigateTo({
      url: '/pages/rewards/rewards'
    });
  },

  // 显示免责声明
  showDisclaimer() {
    wx.showModal({
      title: '免责声明',
      content: '本小程序提供的所有内容仅供学习交流使用，不代表本平台观点。用户在使用过程中因任何原因导致的损失，本平台不承担任何法律责任。使用本平台即表示您已同意本声明的所有内容。',
      confirmText: '我知道了',
      showCancel: false,
      confirmColor: '#07c160'
    });
  },

  goToFollow() {
    console.log("跳转");
    wx.navigateTo({
      url: '/pages/follow/follow'
    });
  },

  // 跳转到兑换记录页面
  goToExchangeRecords() {
    if (!this.data.isLoggedIn) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    wx.navigateTo({
      url: '/pages/exchange-records/exchange-records'
    });
  },

  // 跳转到文章列表页面
  gotoShare() {
    console.log('gotoShare called');
    if (!this.data.isLoggedIn) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 检查分享次数
    const shareCount = this.checkShareCount();
    if (shareCount >= 3) {
      wx.showToast({
        title: '今日分享次数已达上限',
        icon: 'none'
      });
      return;
    }

    // 跳转到首页
    wx.switchTab({
      url: '/pages/index/index',
      success: () => {
        wx.showToast({
          title: '请选择文章进行分享',
          icon: 'none',
          duration: 2000
        });
      },
      fail: (error) => {
        console.error('跳转失败：', error);
      }
    });
  },

  // 检查今日分享次数
  checkShareCount() {
    const today = new Date().toDateString();
    const shareRecord = wx.getStorageSync('shareRecord') || {};

    if (shareRecord.date === today) {
      return shareRecord.count || 0;
    }

    // 新的一天，重置分享次数
    wx.setStorageSync('shareRecord', {
      date: today,
      count: 0
    });
    return 0;
  },

  // 更新分享次数
  updateShareCount() {
    const today = new Date().toDateString();
    const shareRecord = wx.getStorageSync('shareRecord') || {};
    const currentCount = shareRecord.count || 0;

    if (currentCount >= 3) {
      wx.showToast({
        title: '今日分享次数已达上限',
        icon: 'none'
      });
      return false;
    }

    wx.setStorageSync('shareRecord', {
      date: today,
      count: currentCount + 1
    });
    return true;
  },

  // GIF拖动相关方法
  onGifStart(e) {
    this.startX = e.touches[0].clientX;
    this.startY = e.touches[0].clientY;
    this.setData({ isDragging: true });
  },

  onGifMove(e) {
    if (!this.data.isDragging) return;

    const touch = e.touches[0];
    let newLeft = this.data.buttonLeft + (touch.clientX - this.startX);
    let newTop = this.data.buttonTop + (touch.clientY - this.startY);

    // 确保不超出屏幕边界
    newLeft = Math.max(0, Math.min(newLeft, this.data.windowWidth - 80));
    newTop = Math.max(0, Math.min(newTop, this.data.windowHeight - 80));

    this.setData({
      buttonLeft: newLeft,
      buttonTop: newTop
    });

    this.startX = touch.clientX;
    this.startY = touch.clientY;
  },

  onGifEnd() {
    this.setData({ isDragging: false });
  },

  // 显示全屏GIF
  showFullScreenGif() {
    this.setData({ showFullGif: true });
    setTimeout(() => {
      this.setData({ showFullGif: false });
    }, 3000);
  },

  // 隐藏全屏GIF
  hideFullScreenGif() {
    this.setData({ showFullGif: false });
  },

  goToAbout() {
    wx.navigateTo({
      url: '/pages/about/about'
    });
  },
});
